#!/usr/bin/env python
# encoding: utf-8
'''
@author: caopeng
@license: (C) Copyright 1999-2017, Fiberhome Telecommunication Technologies Co.,LTD.
@contact: gjzuo@fiberhome.com
@software: garner
@file: get_vnf_info.py
@time: 2018/2/7 16:48
@desc:
'''

# coding=utf8
import os
import psutil
import time
import uuid
import json

cpu = {'user': 0, 'system': 0, 'idle': 0, 'percent': 0}
mem = {'total': 0, 'avaiable': 0, 'percent': 0, 'used': 0, 'free': 0}

# 磁盘名称
disk_id = []
# 将每个磁盘的total used free percent 分别存入到相应的list
disk_total = []
disk_used = []
disk_free = []
disk_percent = []

disk_info = {}

process_list = []


# 获取CPU信息
def get_cpu_info():
    cpu_times = psutil.cpu_times()
    cpu['user'] = cpu_times.user
    cpu['system'] = cpu_times.system
    cpu['idle'] = cpu_times.idle
    cpu['percent'] = psutil.cpu_percent(interval=2)
    return cpu


# 获取内存信息
def get_mem_info():
    mem_info = psutil.virtual_memory()
    mem['total'] = humanbytes(mem_info.total)
    mem['available'] = humanbytes(mem_info.available)
    mem['percent'] = mem_info.percent
    mem['used'] = humanbytes(mem_info.used)
    mem['free'] = humanbytes(mem_info.free)

    return mem


# 获取磁盘
def get_disk_info():
    disk_num = 0
    disk_total_all = 0
    disk_free_total = 0
    disk_used_total = 0
    disk_detail_info = []
    for id in psutil.disk_partitions():
        if 'cdrom' in id.opts or id.fstype == '':
            continue
        disk_name = id.device.split(':')
        s = disk_name[0]
        disk_id.append(s)
        single_disk_info = psutil.disk_usage(id.device)

        disk_total.append(humanbytes(single_disk_info.total))
        disk_used.append(humanbytes(single_disk_info.used))
        disk_free.append(humanbytes(single_disk_info.free))
        disk_percent.append(single_disk_info.percent)

        disk_total_all = disk_total_all + single_disk_info.total
        disk_free_total = disk_free_total + single_disk_info.free
        disk_used_total = disk_used_total + single_disk_info.used
        disk_obj = {
            'symbol': disk_name[0],
            'total': humanbytes(single_disk_info.total),
            'used': humanbytes(single_disk_info.used),
            'free': humanbytes(single_disk_info.free),
            'percent': humanbytes(single_disk_info.percent)
        }
        disk_detail_info.append(disk_obj)

    disk_info = {
        'total': humanbytes(disk_total_all),
        "free": humanbytes(disk_free_total),
        "used": humanbytes(disk_used_total),
        'detail': disk_detail_info
    }

    return disk_info


def humanbytes(B):
   'Return the given bytes as a human friendly KB, MB, GB, or TB string'
   B = float(B)
   KB = float(1024)
   MB = float(KB ** 2) # 1,048,576
   GB = float(KB ** 3) # 1,073,741,824
   TB = float(KB ** 4) # 1,099,511,627,776

   if B < KB:
      return '{0} {1}'.format(B,'Bytes' if 0 == B > 1 else 'Byte')
   elif KB <= B < MB:
      return '{0:.2f} KB'.format(B/KB)
   elif MB <= B < GB:
      return '{0:.2f} MB'.format(B/MB)
   elif GB <= B < TB:
      return '{0:.2f} GB'.format(B/GB)
   elif TB <= B:
      return '{0:.2f} TB'.format(B/TB)


def get_process_list():
    for proc in psutil.process_iter():
        try:
            pinfo = proc.as_dict(attrs=['pid', 'name'])
        except psutil.NoSuchProcess:
            pass
        else:
            process_list.append(pinfo)

    return process_list

def get_mac_address():
    mac=uuid.UUID(int = uuid.getnode()).hex[-12:]
    return ":".join([mac[e:e+2] for e in range(0,11,2)])


if __name__ == '__main__':
    get_cpu_info()
    cpu_status = cpu['percent']
    print u"CPU使用率: %s %%" % cpu_status
    get_mem_info()
    get_process_list()
    mem_status = mem['percent']
    print u"内存使用率: %s %%" % mem_status
    disk_info = get_disk_info()
    for i in range(len(disk_id)):
        print u'%s盘空闲率: %s %%' % (disk_id[i], 100 - disk_percent[i])

    # print cpu
    # print mem
    # print disk_info
    # print process_list

    deviceInfo = {
        "cpuInfo": cpu,
        "memInfo": mem,
        "diskInfo": disk_info,
        "psList": process_list
    }

    print deviceInfo
